<?php
/*
a. 买家确认收货的情况，7日后系统自动结算
b. 从卖家发货的时间算起，7日后系统自动确认收货，10日后系统自动结算。

*/
namespace Admin\Action;
 use Think\Model;
class FinishOrderAction extends BaseAction{
    /**
     * 15天完成的订单金额转到余额
     *  http://www.yushangcn.com/index.php/Admin/FinishOrder/autoReceipt.html
     */
	//自动收货
    public function autoReceipt() {
        $date =  date("Y-m-d",strtotime("-7 day"));
        $res = M("orders")->where('orderStatus=1 and date_format(`upTime`, "%Y-%m-%d") = "' . $date . '"')->select();
       
        foreach ($res as $r) {
            M("orders")->where("orderId={$r['orderId']}")->save(array('orderStatus'=>6,'upTime'=> date("Y-m-d H:i:s"),"isSysReceipt"=>1,"sysReceiptTime"=>date("Y-m-d")));
  
        }

        



    }

    //b. 从卖家发货的时间算起，7日后系统自动确认收货，10日后系统自动结算。
    public function BaffirmFinishOrder() {
        $date =  date("Y-m-d",strtotime("-10 day"));
        $res = M("orders")->where('orderStatus=6 and isSysReceipt=1 and sysReceiptTime = "' . $date . '"')->select();
       
        foreach ($res as $r) {
             $orderArr[] =$r['orderId'];
  
        }

        $m = M('log_user_profit');
        //-3:拒绝退款;,6:订单完成;
        $profits = $m->where('profit > 0 and  profitStatus = 0  and orderId = "' . array('in',$orderArr) . '"')->select();


        foreach ($profits as $v) {

                $oStatus = M("orders")->where(array("orderNo"=>$v['orderNo'],"payType"=>1))->getField("orderStatus") ; 
                $userId = M("shops")->where("shopId={$v['shopId']}")->getField("userId");
         
                $log_order[]  = $v['orderNo'];
             
                 //if  ($userId>0  && in_array($resOrder[0]['orderStatus'],array(-3,2,6)) ) {  
                if ($userId>0 && in_array($oStatus,array(-3,2,6))  ) {
  
                        $v['old_userBalance'] = M('users')->where('userId=' . $userId )->getField('userBalance');   
                        $v['new_userBalance'] = $v['old_userBalance']+ $v['profit'];  //只为日志记录
 
                        error_log("\r\n\r\n".date("Y-m-d H:i:s")." line 58 ：v=".json_encode($v),3,LOG_PATH."finishOrder_".date("Ymd").".log");  

                        $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $v['profit']);  
                        error_log("\r\n\r\n".date("Y-m-d H:i:s")." line 61 ：sql=".M('users')->getLastSql(),3,LOG_PATH."finishOrder_".date("Ymd").".log");  
                     
                        $v['userId'] = $userId;
 
                        error_log("\r\n\r\n".date("Y-m-d H:i:s")." line 65 ： 完成的订单金额转到余额日志：".json_encode($v),3,LOG_PATH."finishOrder_".date("Ymd").".log");        
                        
                        if ($v['isSource'] == 1 && $userId>0) {
                            $this->MlogBalance($userId, $v['profit'], 6, '订单[' . $v['orderNo'] . ']销售收益');
                        } else {
                            $this->MlogBalance($userId, $v['profit'], 5, '订单[' . $v['orderNo'] . ']转售收益');
                        }
                        $m->where('id = ' . $v['id'])->save(array('profitStatus' => 1));
                   
 
                }
        }


    }
    /**
     * 15天完成的订单金额转到余额
     *  http://www.yushangcn.com/index.php/Admin/FinishOrder/upFinishALLOrder.html
     *  -2:未支付;-3:拒绝退款;0:待付款;1:待发货,2:待签收,3:售后申请,4:同意退款,5:已退款,6:订单完成;
     */
    public function upFinishALLOrder() {
        $this->autoReceipt();
        $this->BaffirmFinishOrder();
        $date = date("Y-m-d", strtotime("-7 day"));
     
       
        $MODEL = new Model();
        $m = M('log_user_profit');
        //-3:拒绝退款;,6:订单完成;
        $profits = $m->where('profit > 0 and  profitStatus = 0  and date_format(`createTime`, "%Y-%m-%d") = "' . $date . '"')->select();

 
        foreach ($profits as $v) {

            	$oStatus = M("orders")->where(array("orderNo"=>$v['orderNo'],"payType"=>1))->getField("orderStatus") ; 
                $userId = M("shops")->where("shopId={$v['shopId']}")->getField("userId");
       	 
                $log_order[]  = $v['orderNo'];
             
                 //if  ($userId>0  && in_array($resOrder[0]['orderStatus'],array(-3,2,6)) ) {  
                if ($userId>0 && in_array($oStatus,array(-3,2,6))  ) {
  
                        $v['old_userBalance'] = M('users')->where('userId=' . $userId )->getField('userBalance');   
                        $v['new_userBalance'] = $v['old_userBalance']+ $v['profit'];  //只为日志记录

                        

                        $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $v['profit']);  
                        
                     
                        $v['userId'] = $userId;
 
                              
                        
                        if ($v['isSource'] == 1 && $userId>0) {
                            $this->MlogBalance($userId, $v['profit'], 6, '订单[' . $v['orderNo'] . ']销售收益');
                        } else {
                            $this->MlogBalance($userId, $v['profit'], 5, '订单[' . $v['orderNo'] . ']转售收益');
                        }
                        $m->where('id = ' . $v['id'])->save(array('profitStatus' => 1));
                   
 
                }
        }

       // echo  implode($log_order,",").",结算完成....";
 
    }


    /**
     * 余额日志
     */
    public function MlogBalance($userId, $price, $logType, $logContent = '') {
        $m = M('log_user_balance');
        $typeName = array(1 => '订单支付', 2 => '充值', 3 => '提现', 4 => '退款', 5 => '转售收益', 6 => '销售收益', 8 => '商家退款', 9 => '退回保证金');
        $data = array();
        $data['userId'] = $userId;
        $userBalance=M("Users")->where("userId={$userId}")->getField("userBalance");
        $data['current_balance'] = $userBalance;
        $data['logContent'] = $logContent;
        $data['price'] = $price;
        $data['logType'] = $logType;
        $data['typeName'] = $typeName[$logType];
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $m->add($data);
    
        return $rs;
    }

    


}